<template lang="pug">
  .container
    form(v-if="!$store.state.authUser" @submit.prevent="signin")
      p.error(v-if="formError") {{ formError }}
      p <i>To signin, use <b>demo</b> as username and <b>demo</b> as password.</i>
      p {{$t('sign.username')}}:
        input(type="text" v-model="formUsername" name="username")
      p {{$t('sign.password')}}:
        input(type="password" v-model="formPassword" name="password")
      button(type="submit") {{$t('sign.signin')}}
    div(v-else)
      button(@click="signout") {{$t('sign.signout')}}
</template>

<script>
export default {
  asyncData ({ store }) {
  },
  data() {
    return {
      formError: null,
      formUsername: '',
      formPassword: ''
    }
  },
  computed: {
    locale () {
      return this.$store.state.locale
    }
  },
  methods: {
    async signin() {
      try {
        await this.$store.dispatch('signin', {
          username: this.formUsername,
          password: this.formPassword
        })
        if (this.$store.state.authUser) {
          this.$router.push(this.$store.state.authURL || this.$i18n.path(''))
        }
        this.formUsername = ''
        this.formPassword = ''
        this.formError = null
      } catch (e) {
        this.formError = e.message
      }
    },
    async signout() {
      try {
        await this.$store.dispatch('signout')
        this.$router.push('/')
      } catch (e) {
        this.formError = e.message
      }
    }
  },
}
</script>

<style lang="stylus">
@import '~assets/stylus/variables.styl'
.error
  color: $color-info
</style>
